package com.sdyd.antivirus.controller;

import com.alibaba.fastjson.JSONObject;
import com.sdyd.antivirus.model.UserInfo;
import com.sdyd.antivirus.model.UserInfoKey;
import com.sdyd.antivirus.service.UserInfoService;
import com.sdyd.antivirus.utils.AesEncryptUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("per")
public class UserInfoController {
    Logger logger= LoggerFactory.getLogger(UserInfoController.class);

    @Autowired
    private UserInfoService userInfoService;

    @RequestMapping("test")
    public String test(){
        return "hello";
    }

    @RequestMapping("health")
    public String insertUserInfo(UserInfo userInfo){
        JSONObject obj = new JSONObject();
        obj.put("success",true);
        try {
            //首先验证groupId是否合法
            String groupId = userInfo.getGroupId();
            Map groupInfo = userInfoService.getGroupInfo(groupId);
            Float heatingDegree = userInfo.getHeatingDegree();
            //将手机号码解密,如果不能解密抛出异常，插入失败
            //System.out.println(userInfo.getPhoneNumber());
            //String phone = URLEncoder.encode(userInfo.getPhoneNumber(), "utf-8");//转码
            //phone = URLDecoder.decode(phone, "UTF-8");//解码
            String phone = userInfo.getPhoneNumber();
            AesEncryptUtil.decrypt(phone);
            if(groupInfo == null){
                logger.error("UserInfoController插入用户信息失败：组织id不合法");
                obj.put("success",false);
            }else if(heatingDegree != null && (heatingDegree.floatValue()<35.0 || heatingDegree.floatValue()>42.0) ){
                logger.error("UserInfoController插入用户信息失败：体温范围错误");
                obj.put("success",false);
            }else {
                userInfoService.insertUserInfo(userInfo);
            }

        } catch (Exception e) {
            e.printStackTrace();
            logger.error("UserInfoController插入用户信息失败："+e.getMessage());
            obj.put("success",false);
        }
        return obj.toString();
    }

    @RequestMapping("getGroupInfo")
    public String getGroupInfo(String groupId){
        JSONObject obj = new JSONObject();
        Map groupInfo = userInfoService.getGroupInfo(groupId);
        System.out.println(groupInfo);
        if(groupInfo != null){
            obj.put("success",true);
            obj.put("groupInfo",groupInfo);
        }else{
            obj.put("success",false);
        }
        return obj.toString();
    }

}
